import { Component, OnInit, OnDestroy } from '@angular/core';
import { AddVMSService } from '../add-vms.service';
import { NotificationService, BullySubjectService, ToolsService } from 'app/shared/service';
import { Subject, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap, filter } from 'rxjs/operators';
import { DisseminationService } from '../../../dissemination-management.service';

@Component({
    selector: 'itmp-vms-library',
    templateUrl: './vms-library.component.html',
    styleUrls: ['./vms-library.component.css', '../add-vms.component.css']
})
export class VmsLibraryComponent implements OnInit, OnDestroy {
    searchData = {
        messageCategory: null,
        keyword: null
    };
    listOfData: any[] = [];
    search$ = new Subject<string>();
    subscripions: Subscription[] = [];
    isShowVietName = false;

    constructor(
        public addService: AddVMSService,
        private msg: NotificationService,
        private diss: DisseminationService,
        private tools: ToolsService
    ) {}

    ngOnInit() {
        this.searchPipeSet();
        this.getData();
        if (localStorage.getItem('itmp_lang') === 'vi') {
            this.isShowVietName = true;
        } else {
            this.isShowVietName = false;
        }
    }

    ngOnDestroy() {
        this.subscripions.forEach(item => {
            item.unsubscribe();
        });
    }

    getData() {
        this.searchData.keyword = this.searchData.keyword === '' ? null : this.searchData.keyword;
        const params = {
            condition: {
                category_id: null,
                category_name: this.searchData.messageCategory,
                message_id: null,
                template_id: null,
                template_name: this.searchData.keyword
            },
            pageNum: 1,
            pageSize: 1000000
        };
        this.diss.getMessageLibraryList(params).subscribe(res => {
            const content = res.data;
            if (!content) {
                this.listOfData = [];
                return;
            }
            this.listOfData = content.content;
        });
    }

    // 防抖函数注册
    searchPipeSet() {
        const subscripion = this.search$.pipe(debounceTime(1000), distinctUntilChanged()).subscribe((kw: any) => {
            this.getData();
        });
        this.subscripions.push(subscripion);
    }

    // 搜索(防抖)
    onSearch(): void {
        this.search$.next(this.searchData.keyword);
    }

    clickTR(index) {
        this.listOfData.forEach((item, i) => {
            item.active = false;
            if (i === index) {
                item.active = true;
                this.addService.selectVMSLibrary = item;
            }
        });
    }

    // 点击添加按钮
    copyToInfo() {
        if (!this.addService.selectVMSLibrary) {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.select_notify' });
            return;
        }
        this.addService.setShowPage(0);
        const selectVMSLibrary = this.addService.selectVMSLibrary;
        const { category, msgDisplayId, msgId, template } = selectVMSLibrary;
        const templatePages = [],
            graphics = [],
            texts = [];

        // graphics fill
        if (selectVMSLibrary.graphics && selectVMSLibrary.graphics.length) {
            selectVMSLibrary.graphics.forEach(g => {
                const page = g.pageSeq - 1;
                if (!graphics[page]) {
                    graphics[page] = [];
                }
                graphics[page].push({
                    messageId: g.messageId,
                    graphicSeq: g.graphicSeq,
                    vmsGraphic: g.vmsGraphic
                });
            });
        }
        // text fill
        if (selectVMSLibrary.texts && selectVMSLibrary.texts.length) {
            selectVMSLibrary.texts.forEach(t => {
                const page = t.pageSeq - 1;
                if (!texts[page]) {
                    texts[page] = [];
                }
                texts[page].push(this.tools.isClone(t));
            });
        }
        // fill templatePages
        if (template.templatePages && template.templatePages.length) {
            const tp = template.templatePages[0];
            const templateGraphics = [];
            const templateTexts = [];
            (tp.templateGraphics || []).forEach(tg => {
                const page = tg.pageSeq - 1;
                if (!templateGraphics[page]) {
                    templateGraphics[page] = [];
                }
                templateGraphics[page].push(this.tools.isClone(tg));
            });
            (tp.templateTexts || []).forEach(tt => {
                const page = tt.pageSeq - 1;
                if (!templateTexts[page]) {
                    templateTexts[page] = [];
                }
                templateTexts[page].push(this.tools.isClone(tt));
            });
            const pages = Math.max(graphics.length, texts.length, templateGraphics.length, templateTexts.length);
            for (let i = 0; i < pages; i++) {
                const temp = {
                    pageSeq: i + 1,
                    graphics: graphics[i] || [],
                    texts: texts[i] || [],
                    // templateId: item.templateId,
                    templateGraphics: templateGraphics[i],
                    templateTexts: templateTexts[i]
                };
                templatePages.push(temp);
            }
        }
        const displayMessage = {
            deviceConfig: template.deviceConfig,
            category,
            msgDisplayId,
            msgId,
            templateId: template.templateId,
            templatePages,
            deviceInfo: {
                width: template.deviceConfig.width,
                height: template.deviceConfig.height
            }
        };
        this.addService.setDisplayMessage(displayMessage);

        this.listOfData.forEach(item => {
            if (item.active) {
                item.active = false;
                return;
            }
        });
        this.addService.setVMSLibrary(null);
    }
}
